<style>
    .Student_information {
        margin-top: 25px;
    }

    .head {
        display: flex;
        justify-content: space-between;
        height: 38px;
        line-height: 38px;
    }
</style>
<div class="Student_information layui-container">

    <blockquote class="layui-elem-quote layui-text">
        若需修改学生所属学院班级年级等信息，请依次选中后再点立即修改
        <br>
    </blockquote>

    <!-- 学生信息头部 -->
    <div class="head">
        <h3><strong>学生相册信息查看与修改</strong></h3>
    </div>
    <!-- 分割线 -->
    <div>
        <hr class="layui-border-black">
    </div>
    <form action="" class="layui-form" style="margin-top: 20px;">
        <div class="layui-form-item">
            <label class="layui-form-label">学号</label>
            <div class="layui-input-block">
                <input type="text" name="role" autocomplete="off" class="layui-input" value="学号"
                       id="userName-input-text">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">姓名</label>
            <div class="layui-input-block">
                <input type="text" name="role" autocomplete="off" class="layui-input" value="姓名"
                       id="fullName-input-text">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">角色</label>
            <div class="layui-input-block">
                <input type="text" name="role" autocomplete="off" class="layui-input" value="角色" id="role-input-text">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">学院</label>
            <div class="layui-input-block">
                <select name="college" lay-verify="" id="college-select" lay-filter="college-select">
                    <option value="">请选择一个学院</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">专业</label>
            <div class="layui-input-block">
                <select name="major" lay-verify="" id="major-select" lay-filter="major-select">
                    <option value="">需要先选择学院</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">年级</label>
            <div class="layui-input-block">
                <select name="grade" lay-verify="" id="grade-select" lay-filter="grade-select">
                    <option value="">需要先选择专业</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">班级</label>
            <div class="layui-input-block">
                <select name="class" lay-verify="" id="class-select" lay-filter="class-select">
                    <option value="">需要先选择年级</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit="" lay-filter="save">立即修改</button>
                <button class="layui-btn" type="button" id="reset-password-btn">重置密码</button>
            </div>
        </div>
    </form>
    <!-- 分割线 -->
    <div>
        <hr class="layui-border-black">
    </div>
    <!-- 学生相册信息 -->
    <h3><strong>学生相册信息查看与修改</strong></h3>
    <script type="text/html" id="toolbarDemo1">
        <div class="layui-btn-container">
        </div>
    </script>

    <table class="layui-hide" id="currentTableId1" lay-filter="currentTableFilter1"></table>
    <script type="text/html" id="currentTableBar1">
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="preview">查看</a>
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="accept">设置为审核通过</a>
        <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="reject">设置为审核不通过</a>
    </script>
</div>

<script>
    layui.use(['form', 'layedit', 'laydate'], function () {
        var form = layui.form,
            layer = layui.layer,
            layedit = layui.layedit,
            laydate = layui.laydate;

        /**
         * 初始化表单，要加上，不然刷新部分组件可能会不加载
         */
        form.render();


        //学生信息初始化
        //不允许修改部分内容
        jq1111('#role-input-text').attr("disabled", "disabled");
        jq1111('#userName-input-text').attr("disabled", "disabled");
        jq1111('#fullName-input-text').attr("disabled", "disabled");

        //定义变量
        var userId = localStorage.getItem('selectedUserId');
        var userData;
        //获取学生信息
        jq1111.ajax({
            type: "GET",
            async: false,
            crossDomain: true,
            url: BasePath + "api/Account/" + userId,
            contentType: "application/json",
            xhrFields: {
                withCredentials: true
            },
            success: function (message) {
                console.log(message);
                userData = message.data;
                layer.msg(message.msg, function () {
                });
            },
            error: function (message) {
                console.log(message.responseJSON);
                layer.msg('失败:' + message.responseJSON.msg);
            },
        });
        //给表单赋值
        //学号 姓名 角色 赋初值
        jq1111('#userName-input-text').val(userData.userName);
        jq1111('#fullName-input-text').val(userData.fullName);
        jq1111('#role-input-text').val(function () {
            var result = "";
            var roles = userData.roles;
            roles.forEach(function (role) {
                result += role;
                result += " ";
            })
            return result;
        });
        //获取学院
        jq1111.ajax({
            type: "GET",
            async: false,
            crossDomain: true,
            url: BasePath + "api/School/Colleges",
            contentType: "application/json",
            dataType: "json",
            xhrFields: {
                withCredentials: true
            },
            success: function (message) {
                var colleges = message.data;
                console.log(message);
                colleges.forEach(function (college) {
                    console.log(college)
                    jq1111("#college-select").append('' +
                        '<option value="' +
                        college.id +
                        '">' +
                        college.name +
                        '</option>' +
                        '')
                })
                //再次初始化form
                form.render();
            },
            error: function (message) {
                console.log(message.responseJSON);
                layer.msg('失败:' + message.responseJSON.message);
            },
        });
        console.log('userdata', userData)
        if (userData.major !== null) {
            jq1111("#college-select").val(userData.college.id);
        }
        form.render();
        //获取年级
        jq1111.ajax({
            type: "GET",
            async: false,
            crossDomain: true,
            url: BasePath + "api/School/Grades",
            contentType: "application/json",
            dataType: "json",
            xhrFields: {
                withCredentials: true
            },
            success: function (message) {
                console.log(message)
                var grades = message.data;
                grades.forEach(function (grade) {
                    jq1111("#grade-select").append('' +
                        '<option value="' +
                        grade.id +
                        '">' +
                        grade.display +
                        '</option>' +
                        '')
                })
                //再次初始化form
                form.render();
            },
            error: function (message) {
                console.log(message.responseJSON);
                layer.msg('失败:' + message.responseJSON.message);
            },
        });
        if (userData.major !== null) {
            jq1111("#grade-select").val(userData.grade.id);
            //获取专业
            jq1111.ajax({
                type: "GET",
                async: false,
                crossDomain: true,
                url: BasePath + "api/School/Majors?collegeId=" + userData.major.id,
                contentType: "application/json",
                dataType: "json",
                xhrFields: {
                    withCredentials: true
                },
                success: function (message) {
                    var majors = message.data;
                    majors.forEach(function (major) {
                        jq1111("#major-select").append('' +
                            '<option value="' +
                            major.id +
                            '">' +
                            major.name +
                            '</option>' +
                            '')
                    });
                    jq1111("#major-select").val(userData.major.id);

                },
                error: function (message) {
                    console.log(message.responseJSON);
                },
            });

            //获取班级
            jq1111.ajax({
                type: "GET",
                async: false,
                crossDomain: true,
                url: BasePath + 'api/School/QueryClasses?majorId=' + jq1111('#major-select').val() + '&gradeId=' + jq1111('#grade-select').val(),
                contentType: "application/json",
                dataType: "json",
                xhrFields: {
                    withCredentials: true
                },
                success: function (message) {
                    var classes = message.data;
                    classes.forEach(function (classt) {
                        jq1111("#class-select").append('' +
                            '<option value="' +
                            classt.id +
                            '">' +
                            classt.name +
                            '</option>' +
                            '')
                    });

                },
                error: function (message) {
                    console.log(message.responseJSON);
                },
            });
        }

        if (userData.major !== null) {
            jq1111("#major-select").val(userData.major.id);
            jq1111("#class-select").val(userData.class.id);
            //再次初始化form
            form.render('select');
        }


        //监听学院的select事件来获取专业
        form.on('select(college-select)', function (data) {
            console.log(data)
            if (data.value == "") {
                jq1111("#major-select").attr("disabled", "disabled");
                jq1111("#class-select").attr("disabled", "disabled");

                form.render('select');
            } else {
                jq1111("#major-select").removeAttr("disabled");
                //移除之前添加的专业
                var children = jq1111("#major-select").children();
                for (i = 1; i < children.length; i++) {
                    children.eq(i).remove();
                }
                //获取专业
                jq1111.ajax({
                    type: "GET",
                    async: false,
                    crossDomain: true,
                    url: BasePath + "api/School/Majors?collegeId=" + data.value,
                    contentType: "application/json",
                    dataType: "json",
                    xhrFields: {
                        withCredentials: true
                    },
                    success: function (message) {
                        var majors = message.data;
                        majors.forEach(function (major) {
                            jq1111("#major-select").append('' +
                                '<option value="' +
                                major.id +
                                '">' +
                                major.name +
                                '</option>' +
                                '')
                        });
                        if (userData.major !== null) {
                            jq1111("#major-select").val(userData.major.id);
                        }
                        //再次初始化form
                        form.render('select');
                    },
                    error: function (message) {
                        console.log(message.responseJSON);
                    },
                });
            }
        });

        //监听专业的select事件来设置年级
        form.on('select(major-select)', function (data) {
            console.log(data)
            if (data.value == "") {
                jq1111('#grade-select').attr("disabled", "disabled");
                form.render('select');
            } else {
                jq1111('#grade-select').removeAttr("disabled");
            }
        });

        //监听年级的select事件来设置班级
        form.on('select(grade-select)', function (data) {
            console.log(data)
            if (data.value == "") {
                jq1111('#class-select').attr("disabled", "disabled");
                form.render('select');
            } else {
                jq1111('#class-select').removeAttr("disabled");
                //移除之前添加的班级
                var children = jq1111("#class-select").children();
                for (i = 1; i < children.length; i++) {
                    children.eq(i).remove();
                }
                console.log('gradeid', jq1111('#grade-select-search'))
                //获取班级
                jq1111.ajax({
                    type: "GET",
                    async: false,
                    crossDomain: true,
                    url: BasePath + 'api/School/QueryClasses?majorId=' + jq1111('#major-select').val() + '&gradeId=' + jq1111('#grade-select').val(),
                    contentType: "application/json",
                    dataType: "json",
                    xhrFields: {
                        withCredentials: true
                    },
                    success: function (message) {
                        var classes = message.data;
                        classes.forEach(function (classt) {
                            jq1111("#class-select").append('' +
                                '<option value="' +
                                classt.id +
                                '">' +
                                classt.name +
                                '</option>' +
                                '')
                        });
                        if (userData.major !== null) {
                            jq1111("#class-select").val(userData.class.id)
                        }
                        ;
                        //再次初始化form
                        form.render('select');
                    },
                    error: function (message) {
                        console.log(message.responseJSON);
                    },
                });
            }

        });
        form.render('select');//select是固定写法 不是选择器


        //日期
        laydate.render({
            elem: '#date'
        });
        laydate.render({
            elem: '#date1'
        });

        //创建一个编辑器
        var editIndex = layedit.build('LAY_demo_editor');

        //自定义验证规则
        form.verify({
            title: function (value) {
                if (value.length < 5) {
                    return '标题至少得5个字符啊';
                }
            },
            pass: [
                /^[\S]{6,12}$/, '密码必须6到12位，且不能出现空格'
            ],
            content: function (value) {
                layedit.sync(editIndex);
            }
        });

        //监听指定开关
        form.on('switch(switchTest)', function (data) {
            layer.msg('开关checked：' + (this.checked ? 'true' : 'false'), {
                offset: '6px'
            });
            layer.tips('温馨提示：请注意开关状态的文字可以随意定义，而不仅仅是ON|OFF', data.othis)
        });

        //监听提交
        form.on('submit(save)', function (data) {
            jq1111.ajax({
                type: "POST",
                crossDomain: true,
                url: BasePath + "api/Account/UpdateStudentInfo",
                contentType: "application/json",
                dataType: "json",
                xhrFields: {
                    withCredentials: true
                },
                data: JSON.stringify(
                    {
                        "classId": jq1111('#class-select').val(),
                        "userId": userId
                    }
                ),
                success: function (message) {
                    console.log(message);
                    layer.msg(message.msg, function () {
                    });
                },
                error: function (message) {
                    console.log(message.responseJSON);
                    layer.msg('失败:' + message.responseJSON.msg);
                },
            });
            return false;
        });

        //重置密码事件

        jq1111("#reset-password-btn").click(resetPassword);

        function resetPassword() {
            layer.prompt({
                formType: 2,
                value: '',
                title: '请输入新的密码',
            }, function (value, index, elem) {
                console.log('new password', value)
                jq1111.ajax({
                    type: "POST",
                    crossDomain: true,
                    url: BasePath + "api/Account/PassWord/Reset",
                    contentType: "application/json",
                    dataType: "json",
                    xhrFields: {
                        withCredentials: true
                    },
                    data: JSON.stringify(
                        {
                            "NewPassword": value,
                            "id": userId
                        }
                    ),
                    success: function (message) {
                        console.log(message);
                        layer.msg(message.msg, function () {
                        });
                    },
                    error: function (message) {
                        console.log(message.responseJSON);
                        layer.msg('失败:' + message.responseJSON.msg);
                    },
                });

                layer.close(index);
            });


        }
    });

    // 学生相册信息表
    layui.use(['form', 'table', 'miniPage', 'element'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            miniPage = layui.miniPage;

        var userId = localStorage.getItem('selectedUserId');

        table.render({
            elem: '#currentTableId1',
            //TODO 暂时没数据来测试，有数据了再调试bug
            url: BasePath + 'api/PersonalAlbum/GetByCreatorId?creatorId=' + userId,
            // url: 'api/edit.json',
            toolbar: '#toolbarDemo1',
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [
                [{
                    type: "checkbox",
                    width: 50
                }, {
                    field: 'id',
                    width: 120,
                    title: 'ID',
                }, {
                    field: 'title',
                    width: 80,
                    title: '标题'
                },
                    //     {
                    //     field: 'sign',
                    //     title: '标签',
                    //     minWidth: 150
                    // },
                    {
                        field: 'description',
                        width: 100,
                        title: '简介',
                        sort: true
                    },
                    {
                        field: 'isPublic',
                        width: 100,
                        title: '是否公开',
                        sort: true
                    },
                    {
                        field: 'reviewState',
                        width: 100,
                        title: '审核状态',
                        sort: true
                    },
                    {
                        title: '操作',
                        minWidth: 150,
                        toolbar: '#currentTableBar1',
                        align: "center"
                    }]
            ],
            limits: [10, 15, 20, 25, 50, 100],
            limit: 15,
            page: true,
            skin: 'line'
        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            var result = JSON.stringify(data.field);
            layer.alert(result, {
                title: '最终的搜索信息'
            });

            //执行搜索重载
            table.reload('currentTableId1', {
                page: {
                    curr: 1
                },
                where: {
                    searchParams: result
                }
            }, 'data');

            return false;
        });

        /**
         * toolbar事件监听
         */
        table.on('toolbar(currentTableFilter1)', function (obj) {
            if (obj.event === 'add') { // 监听添加操作
                var content = miniPage.getHrefContent('page/table/add.html');
                var openWH = miniPage.getOpenWidthHeight();

                var index = layer.open({
                    title: '添加用户',
                    type: 1,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: [openWH[0] + 'px', openWH[1] + 'px'],
                    offset: [openWH[2] + 'px', openWH[3] + 'px'],
                    content: content,
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
            } else if (obj.event === 'delete') { // 监听删除操作
                var checkStatus = table.checkStatus('currentTableId1'),
                    data = checkStatus.data;
                layer.alert(JSON.stringify(data));
            }
        });

        //监听表格复选框选择
        table.on('checkbox(currentTableFilter1)', function (obj) {
            console.log(obj)
        });

        table.on('tool(currentTableFilter1)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                layer.confirm('编辑', function (index) {
                    layer.close(index);
                });
                return false;
            } else if (obj.event === 'delete') {
                layer.confirm('真的删除行么', function (index) {
                    obj.del();
                    layer.close(index);
                });
            }else if (obj.event === 'preview') {
                window.location = 'page/new-show.html?albumId='+data.id;
            }else if (obj.event === 'accept') {
                if(acceptAlbum(data.id)){
                    alert("操作成功")
                    table.reload('currentTableId1', {
                        page: {
                            curr: 1
                        },
                        where: {
                            searchParams: result
                        }
                    }, 'data');
                }
                else {
                    alert("失败");
                }

            }else if (obj.event === 'reject') {
                if(rejectAlbum(data.id)){
                    alert("操作成功")
                    table.reload('currentTableId1', {
                        page: {
                            curr: 1
                        },
                        where: {
                            searchParams: result
                        }
                    }, 'data');
                }else {
                    alert("失败");
                }
            }
        });

    });
</script>